package com.atguigu.gmail.manage.util;

import com.atguigu.gmail.api.ConstNum;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

public class PmsUpLoadUtil {
    public static String uploadImage(MultipartFile multipartFile) {

        String imgUrl = ConstNum.IMG_BASE_URL;
        String tracker = PmsUpLoadUtil.class.getResource("/tracker.conf").getPath();
        try {
            ClientGlobal.init(tracker);
        } catch (Exception e) {
            e.printStackTrace();
        }

        TrackerClient trackerClient = new TrackerClient();

        //获得一个trackerServer的实例
        TrackerServer trackerServer = null;
        try {
            trackerServer = trackerClient.getConnection();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        //通过tracker获得一个storage连接客户端
        StorageClient storageClient = new StorageClient(trackerServer, null);

        //获取图片的二进制流

        try {
            byte[] bytes = multipartFile.getBytes();
            //截取文件后缀名
            String originalFilename = multipartFile.getOriginalFilename();
            int i = originalFilename.lastIndexOf(".");
            String extName = originalFilename.substring(i + 1);

            String[] uploadInfos = new String[0];

            uploadInfos = storageClient.upload_file(bytes, extName, null);

            for (String uploadInfo : uploadInfos) {
                imgUrl += "/" + uploadInfo;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return imgUrl;
    }
}
